import 'dart:convert';

import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_picker/picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/entity/support_bank_entity.dart';
import 'package:taonile/utils/singleton_manager.dart';

import '../http/api.dart';
import '../routers/routers.dart';
import '../views/dialog_manager.dart';

///
/// 添加银行卡
///
class MineBankcardAdd extends StatefulWidget {
  var accountId = '';

  MineBankcardAdd({Key? key, this.accountId = ''}) : super(key: key);

  @override
  State<MineBankcardAdd> createState() => _MineBankcardAddState();
}

class _MineBankcardAddState extends State<MineBankcardAdd> {
  var _name = '';
  var idCard = '';
  var bankCard = '';
  var bankName = '点击选择开户行';
  var bankId = '';
  var bankSubName = '';
  var _phone = '';

  // var _area = '点击选择省市区';
  // var province = '';
  // var city = '';
  // var province_name = '';
  // var city_name = '';

  List<SupportBankData> banks = [];

  @override
  void initState() {
    super.initState();
    getdatas();

    if (widget.accountId.isNotEmpty) {
      setState(() {
        _name = SingletonManager.instance.currentBankData.realName;
        idCard = SingletonManager.instance.currentBankData.idNumber;
        bankCard = SingletonManager.instance.currentBankData.bankNumber;
        bankName = SingletonManager.instance.currentBankData.bankName;
        bankId = SingletonManager.instance.currentBankData.bankName;
        bankSubName = SingletonManager.instance.currentBankData.bankBranch;
        _phone = SingletonManager.instance.currentBankData.mobile;
        // _area =
        //     '${SingletonManager.instance.currentBankData.provinceName}${SingletonManager.instance.currentBankData.cityName}';
        //
        // province = SingletonManager.instance.currentBankData.province;
        // city = SingletonManager.instance.currentBankData.city;
        // province_name = SingletonManager.instance.currentBankData.provinceName;
        // city_name = SingletonManager.instance.currentBankData.cityName;
      });
    }
  }

  getdatas() async {
    dynamic result = await Api.bankList();
    SupportBankEntity entity = SupportBankEntity.fromJson(result);
    setState(() {
      banks.clear();
      banks.addAll(entity.data);
    });
  }

  addReceipt() async {
    FocusManager.instance.primaryFocus?.unfocus();
    if (_name.isEmpty) {
      EasyLoading.showToast("请输入持卡人姓名");
      return;
    }
    if (idCard.length < 11) {
      EasyLoading.showToast("请输入正确的身份证");
      return;
    }
    if (bankCard.length < 16) {
      EasyLoading.showToast("请输入16-19位银行卡号");
      return;
    }
    if (bankName == '点击选择开户行') {
      EasyLoading.showToast("请选择开户银行");
      return;
    }
    // if (_area == '点击选择省市区') {
    //   EasyLoading.showToast("请选择开户城市");
    //   return;
    // }
    if (bankSubName.length < 4) {
      EasyLoading.showToast("请输入开户支行");
      return;
    }
    if (_phone.length < 11) {
      EasyLoading.showToast("请输入正确的手机号");
      return;
    }
    var param = {
      'real_name': _name,
      'id_number': idCard,
      'bank_number': bankCard,
      'bank_name': bankId,
      // 'province': province,
      // 'city': city,
      // 'district': '0',
      'bank_branch': bankSubName,
      'mobile': _phone,
    };

    dynamic result;
    if (widget.accountId.isEmpty) {
      result = await Api.addBankCard(param);
    } else {
      param['id'] = widget.accountId;
      result = await Api.upBankCard(param);
    }
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast(widget.accountId.isEmpty ? "添加成功" : '修改成功');
      Routes.router.pop(context, {'result': 1});
    }
  }

  // deleteReceipt() async {
  //   dynamic result = await Api.delReceipt({'id':''});
  //   var jsonResult = jsonDecode(jsonEncode(result));
  //   if (jsonResult['code'] == 1) {
  //     EasyLoading.showToast("删除成功");
  //     Routes.router.pop(context, {'result': 1});
  //   }
  // }

  // getCityResult() async {
  //   // type 1
  //   Result? result = await CityPickers.showCityPicker(
  //     showType: ShowType.pc,
  //     context: context,
  //     height: 600.w,
  //     barrierOpacity: 0.5,
  //     theme: Theme.of(context).copyWith(),
  //   );
  //   if (result != null) {
  //     String str = '${result.provinceName}-${result.cityName}';
  //     province_name = result.provinceName!;
  //     city_name = result.cityName!;
  //     province = result.provinceId!;
  //     city = result.cityId!;
  //     setState(() {
  //       _area = str;
  //     });
  //   }
  // }

  chooseBank(BuildContext context) async {
    Picker(
        adapter: PickerDataAdapter(
            pickerData: List.generate(banks.length, (index) => banks[index].name), isArray: false),
        height: 450.w,
        headerDecoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.w),
            topRight: Radius.circular(20.w),
          ),
        ),
        itemExtent: 70.w,
        confirmText: '确定',
        cancelText: '取消',
        columnPadding: EdgeInsets.all(15.w),
        onConfirm: (picker, list) {
          // LogUtil.v(SingletonManager.instance.orderCancelReason[list[0]]);
          setState(() {
            bankName = banks[list[0]].name;
            bankId = banks[list[0]].id;
          });
        }).showModal(context, backgroundColor: Colors.transparent);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Config.colorBg2,
        appBar: AppBar(
          title: Text(widget.accountId.isEmpty ? '添加银行卡' : '编辑银行卡'),
          centerTitle: true,
        ),
        body: Container(
          width: double.infinity,
          height: double.infinity,
          margin: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
          child: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                  decoration: BoxDecoration(
                    color: (Config.colorWhite),
                    borderRadius: BorderRadius.circular(10.w),
                  ),
                  child: Column(
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            width: 140.w,
                            child: Text(
                              "持卡人姓名",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 485.w,
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            child: TextField(
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              maxLength: 20,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _name = value;
                                });
                              },
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请输入持卡人姓名",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                              controller: TextEditingController.fromValue(
                                TextEditingValue(
                                  text: _name,
                                  selection: TextSelection.fromPosition(
                                    TextPosition(
                                        // affinity: TextAffinity.downstream,
                                        offset: _name.length),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Divider(
                        color: Config.colorDivider,
                        height: 40.w,
                        thickness: 2.w,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            width: 140.w,
                            child: Text(
                              "身份证号码",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 485.w,
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            child: TextField(
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              maxLength: 18,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  idCard = value;
                                });
                              },
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请输入身份证号码",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                              controller: TextEditingController.fromValue(
                                TextEditingValue(
                                  text: idCard,
                                  selection: TextSelection.fromPosition(
                                    TextPosition(
                                        // affinity: TextAffinity.downstream,
                                        offset: idCard.length),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Divider(
                        color: Config.colorDivider,
                        height: 40.w,
                        thickness: 2.w,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            width: 140.w,
                            child: Text(
                              "银行卡号",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 485.w,
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            child: TextField(
                              keyboardType: TextInputType.number,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              maxLength: 19,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  bankCard = value;
                                });
                              },
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              inputFormatters: [
                                FilteringTextInputFormatter.allow(RegExp("[0-9]")),
                              ],
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请输入银行卡号",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                              controller: TextEditingController.fromValue(
                                TextEditingValue(
                                  text: bankCard,
                                  selection: TextSelection.fromPosition(
                                    TextPosition(
                                        // affinity: TextAffinity.downstream,
                                        offset: bankCard.length),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Divider(
                        color: Config.colorDivider,
                        height: 40.w,
                        thickness: 2.w,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            width: 140.w,
                            child: Text(
                              "开户行",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          InkWell(
                            onTap: () {
                              chooseBank(context);
                            },
                            child: Container(
                              width: 450.w,
                              margin: EdgeInsets.symmetric(vertical: 5.w),
                              child: Text(
                                bankName,
                                style: TextStyle(fontSize: 25.sp),
                              ),
                            ),
                          ),
                          Icon(
                            Icons.arrow_forward_ios,
                            size: 25.w,
                          ),
                        ],
                      ),
                      Divider(
                        color: Config.colorDivider,
                        height: 40.w,
                        thickness: 2.w,
                      ),
                      // Row(
                      //   crossAxisAlignment: CrossAxisAlignment.center,
                      //   children: [
                      //     Container(
                      //       margin: EdgeInsets.symmetric(vertical: 5.w),
                      //       width: 140.w,
                      //       child: Text(
                      //         "开户城市",
                      //         style: TextStyle(fontSize: 25.sp),
                      //       ),
                      //     ),
                      //     Padding(
                      //       padding: EdgeInsets.only(left: 30.w),
                      //     ),
                      //     InkWell(
                      //       onTap: () {
                      //         getCityResult();
                      //       },
                      //       child: Container(
                      //         width: 450.w,
                      //         margin: EdgeInsets.symmetric(vertical: 5.w),
                      //         child: Text(
                      //           _area,
                      //           style: TextStyle(fontSize: 25.sp),
                      //         ),
                      //       ),
                      //     ),
                      //     Icon(
                      //       Icons.arrow_forward_ios,
                      //       size: 25.w,
                      //     ),
                      //   ],
                      // ),
                      // Divider(
                      //   color: Config.colorDivider,
                      //   height: 40.w,
                      //   thickness: 2.w,
                      // ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            width: 140.w,
                            child: Text(
                              "开户支行",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 485.w,
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            child: TextField(
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              maxLength: 50,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  bankSubName = value;
                                });
                              },
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请填输入开户支行名称",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                              controller: TextEditingController.fromValue(
                                TextEditingValue(
                                  text: bankSubName,
                                  selection: TextSelection.fromPosition(
                                    TextPosition(
                                        // affinity: TextAffinity.downstream,
                                        offset: bankSubName.length),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Divider(
                        color: Config.colorDivider,
                        height: 40.w,
                        thickness: 2.w,
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            width: 140.w,
                            child: Text(
                              "预留手机",
                              style: TextStyle(fontSize: 25.sp),
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 30.w),
                          ),
                          Container(
                            width: 485.w,
                            margin: EdgeInsets.symmetric(vertical: 5.w),
                            child: TextField(
                              keyboardType: TextInputType.phone,
                              textAlign: TextAlign.justify,
                              obscureText: false,
                              maxLength: 11,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _phone = value;
                                });
                              },
                              style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                              decoration: const InputDecoration(
                                hintStyle: TextStyle(color: Config.colorText3),
                                hintText: "请输入银行卡预留手机号",
                                counterText: '',
                                isDense: true,
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                              ),
                              controller: TextEditingController.fromValue(
                                TextEditingValue(
                                  text: _phone,
                                  selection: TextSelection.fromPosition(
                                    TextPosition(
                                        // affinity: TextAffinity.downstream,
                                        offset: _phone.length),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 750.w,
                  height: 100.w,
                  padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 8.w),
                  margin: EdgeInsets.only(top: 45.w),
                  child: ElevatedButton(
                    clipBehavior: Clip.antiAlias,
                    onPressed: () => {addReceipt()},
                    style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                    child: Text(widget.accountId.isEmpty ? '确认添加' : '确认修改'),
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}
